package com.gy.springboot.controller;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.gy.springboot.entity.TUser;
import com.gy.springboot.repository.TUserRepository;

@RestController
public class JpaUserController {

    @Autowired
    private TUserRepository tUserRepository;

    /**
     * @author GY
     * @date 2018年10月29日
     * @说明:getOne是返回一个实体的引用——代理对象，findOne是返回实体
     */
    @GetMapping("/get/user/{id}")
    public TUser getUserById(@PathVariable("id") Integer id) {
        // 使用findOne不会报错，使用getOne 如果TUser类上不加 @JsonIgnoreProperties... 就会报错
        // 见：https://blog.csdn.net/gw816/article/details/80401284#commentBox
        Example<TUser> example = Example.of(new TUser().setId(id));
        Optional<TUser> findOne = tUserRepository.findOne(example);
        if(findOne.isPresent())
            return findOne.get();
        return null;
        // TUser tUser = tUserRepository.getOne(id);
        // System.out.println(tUser);
        // return tUser;
    }

    @GetMapping("/add/user")
    public TUser addUser(TUser tUser) {
        TUser user = tUserRepository.save(tUser);
        return user;
    }

}
